﻿using System;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace FIS.iDET.TemplateCreator
{
    class XmlService
    {
        public static List<DataColumn> ReadXml(string fromFile)
        {
            try
            {
                FileStream fs = new FileStream(fromFile, FileMode.Open);
                XmlTextReader r = new XmlTextReader(fs);

                // array to store processed data
                List<DataColumn> columns = new List<DataColumn>();

                // read column nodes
                while (r.Read())
                {
                    if (r.NodeType == XmlNodeType.Element && r.Name == "template")
                    {
                        // set template properties to global vars
                        // GlobalConstants.TemplateName = r.GetAttribute("name");
                        FormTemplateCreator.zoomFactor = Convert.ToDouble(r.GetAttribute("zoom")) / 100;
                        GlobalVariables.TemplateVersion = r.GetAttribute("version");
                        GlobalVariables.TemplatePageCol = Convert.ToInt32(r.GetAttribute("pagecol"));
                        // break;
                    }
                    // get header text from current node's name
                    if (r.NodeType == XmlNodeType.Element && r.Name == "col")
                    {
                        columns.Add(
                            new DataColumn(
                            r.GetAttribute("fieldname"),
                                Convert.ToInt32(r.GetAttribute("datatype")),
                                Convert.ToInt32(r.GetAttribute("colwidth")),
                                Convert.ToDouble(r.GetAttribute("x")),
                                Convert.ToDouble(r.GetAttribute("y")),
                                Convert.ToDouble(r.GetAttribute("w")),
                                Convert.ToDouble(r.GetAttribute("h"))));
                    }
                    
                }

                fs.Close();

                return columns;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unexpected error while loading template file \"" + fromFile + "\"\nError details: " + ex.Message);
                return null;
            }
        }

        public static void WriteXml(string toFile, DataGridView dataGridView)
        {
            try
            {
                FileStream fs = new FileStream(toFile, FileMode.Create, FileAccess.Write);
                XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);
                w.Formatting = Formatting.Indented;
                w.Indentation = 4;

                w.WriteStartDocument();

                // root node
                // <template zoom="100%" version="2.0">
                w.WriteStartElement("template");
                w.WriteAttributeString("zoom", (FormTemplateCreator.zoomFactor * 100).ToString());
                w.WriteAttributeString("version", GlobalVariables.TemplateVersion);
                if (GlobalVariables.TemplatePageCol !=0)
                {
                    w.WriteAttributeString("pagecol", GlobalVariables.TemplatePageCol.ToString());
                }
                // element nodes
                // <col name="Field Name" datatype="number or text or date" width="100"/>
                // sort columns to display index
                int[] a = new int[dataGridView.ColumnCount];
                int[] b = new int[dataGridView.ColumnCount];

                for (int i = 0; i < dataGridView.ColumnCount; i++)
                {
                    b[i] = dataGridView.Columns[i].DisplayIndex;
                }

                for (int i = 0; i < dataGridView.ColumnCount; i++)
                    for (int j = 0; j < dataGridView.ColumnCount; j++)
                    {
                        if (b[j] == i)
                        {
                            a[i] = j;
                            break;
                        }
                    }

                for (int j = 0; j < dataGridView.ColumnCount; j++)
                {
                    int i = a[j];
                    w.WriteStartElement("col");
                    w.WriteAttributeString("fieldname", dataGridView.Columns[i].HeaderText);
                    w.WriteAttributeString("datatype", getDataTypeShortNameOf(dataGridView.Rows[0].Cells[i].Value.ToString()));
                    w.WriteAttributeString("colwidth", dataGridView.Columns[i].Width.ToString());
                    w.WriteAttributeString("x", GlobalVariables.columns[i].X.ToString());
                    w.WriteAttributeString("y", GlobalVariables.columns[i].Y.ToString());
                    w.WriteAttributeString("w", GlobalVariables.columns[i].W.ToString());
                    w.WriteAttributeString("h", GlobalVariables.columns[i].H.ToString());
                    w.WriteEndElement();
                }

                // close xml tags
                w.WriteEndElement();
                w.WriteEndDocument();

                // close document
                w.Flush();
                fs.Close();

                MessageBox.Show("Template file saved to \"" + toFile + "\" successfully!");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Unexpected error while saving file to \"" + toFile + "\"\nError details: " + ex.Message);
            }
        }

        public static string getDataTypeShortNameOf(string longName)
        {
            if (longName == "Date Time")
                return DataTypeEnum.COLUMN_TYPE_DATE.ToString();
            else if (longName == "Number")
                return DataTypeEnum.COLUMN_TYPE_NUMBER.ToString();
            else
                return DataTypeEnum.COLUMN_TYPE_TEXT.ToString();
        }

        public static string getDataTypeLongNameOf(int shortName)
        {
            switch (shortName)
            {
                case DataTypeEnum.COLUMN_TYPE_DATE:
                    return "Date Time";
                case DataTypeEnum.COLUMN_TYPE_NUMBER:
                    return "Number";
                default:
                    return "General Text";
            }
        }
    }
}
